package com.lijia.ffmpeg4android.intent;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.lijia.ffmpeg4android.model.Crime;

import android.content.Context;

public class CrimeIntentJSONSerializer {
	private Context mContext;
	private String mFilename;
	
	public CrimeIntentJSONSerializer(Context mContext, String mFilename) {
		super();
		this.mContext = mContext;
		this.mFilename = mFilename;
	}
	
	public List<Crime> loadCrimes()
		throws IOException,JSONException {
		List<Crime> crimes = new ArrayList<Crime>();
		BufferedReader reader = null;
		try {
			InputStream in = mContext.openFileInput(mFilename);
			reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder jsonString = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				jsonString.append(line);
			}
			JSONArray array = (JSONArray)new JSONTokener(jsonString.toString()).nextValue();
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonobj = array.getJSONObject(i);
				Crime crime = new Crime(jsonobj);
				crimes.add(crime);
			}
		} catch (FileNotFoundException e) {
			//Ignore this one; it happens when starting fresh
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return crimes;
	}
	
	public void saveCrimes(List<Crime> crimes) 
		throws JSONException,IOException {
		JSONArray array = new JSONArray();
		for (Crime crime : crimes) {
			array.put(crime.toJSON());
		}
		
		Writer writer = null;
		try {
			OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_PRIVATE);
			writer = new OutputStreamWriter(out);
			writer.write(array.toString());
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
	
	public void saveCrimesToExternal() {
		//TODO
	}
}
